<template>
  <el-dialog
    top="30px"
    width="800px"
    title="项目受理"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <table class="table table-borderless table-sm">
      <tbody>
        <tr>
          <td width="16%" class="text-muted">项目名称：</td>
          <td width="34%">{{ relatedData.customer_name }}</td>
          <td width="16%" class="text-muted">项目地址：</td>
          <td width="34%">{{ relatedData.address }}</td>
        </tr>
        <tr>
          <td class="text-muted">负责人：</td>
          <td>{{ relatedData.corp_name }}</td>
          <td class="text-muted">联系电话：</td>
          <td>{{ relatedData.mobile_no }}</td>
        </tr>
        <tr>
          <td class="text-muted">申请金额：</td>
          <td>{{ relatedData.apply_funds || '-' }} 万元</td>
          <td class="text-muted">申请年限：</td>
          <td>{{ relatedData.load_years || '-' }} 年</td>
        </tr>
        <tr>
          <td class="text-muted">推荐机构：</td>
          <td>{{ relatedData.submit_person_name || '-' }}</td>
          <td class="text-muted">推荐时间：</td>
          <td>{{ $utils.dateFormat(relatedData.recommend_time, 'yyyy.MM.dd') || '-' }}</td>
        </tr>
        <tr>
          <td class="text-muted">贷款用途：</td>
          <td colspan="3">{{ relatedData.funds_use_dir || '-' }}</td>
        </tr>
        <tr>
          <td class="text-muted">
            <div class="my-2">是否受理项目：</div>
          </td>
          <td colspan="3">
            <div class="my-2">
              <el-switch
                v-model="putData.is_approval"
                active-color="#67C23A"
                inactive-color="#F56C6C"
                active-value="1"
                :active-text="+putData.is_approval === 1 ? '是' : '否'"
                inactive-value="0"
              ></el-switch>
            </div>
          </td>
        </tr>
        <template v-if="+putData.is_approval === 1">
          <tr>
            <td class="text-muted">业务模式：</td>
            <td colspan="3">
              <span v-if="!isUserTown">直担业务</span>
              <select-gua-type
                v-else
                placeholder="请选择项目类型"
                class="form-control-ml"
                v-model="putData.gua_type"
              ></select-gua-type>
            </td>
          </tr>
          <tr>
            <td class="text-muted">产品选择：</td>
            <td colspan="3">
              <select-credit-product
                placeholder="请选择担保产品（非必填）"
                class="form-control-ml"
                v-model="putData.project_type_id"
                @change="setLoanMode"
                :project-address="relatedData.address_code"
                :project-type="putData.gua_type"
              ></select-credit-product>
            </td>
          </tr>
          <tr v-show="needAccessAgency">
            <td class="text-muted">联保机构：</td>
            <td colspan="3">
              <select-org-credit
                v-model="putData.recommend_service"
                @change="handleAccessAgencyChange"
                :gua-type="putData.gua_type"
                class="form-control-ml"
                placeholder="请选择联保机构"
              ></select-org-credit>
            </td>
          </tr>
          <tr>
            <td class="text-muted">项目负责人A角：</td>
            <td colspan="3">
              <select-staff
                v-model="putData.res_a"
                ref="resA"
                class="form-control-ml"
                placeholder="请选择A角"
              ></select-staff>
            </td>
          </tr>
          <tr>
            <td class="text-muted">项目负责人B角：</td>
            <td colspan="3">
              <select-staff
                v-model="putData.res_b"
                ref="resB"
                class="form-control-ml"
                placeholder="请选择B角"
              ></select-staff>
            </td>
          </tr>
          <tr v-show="[4].includes(+putData.gua_type)">
            <td class="text-muted pt-2">
              <span class="text-danger">*</span>
              风控员：
            </td>
            <td colspan="3">
              <select-staff
                v-model="putData.res_user_id_risk_point"
                :includeJob="['org_r_emp', 'org_r_manage', 'org_dg_risk_manage']"
                ref="risk"
                class="form-control-ml"
                placeholder="请选择项目风控员"
              ></select-staff>
            </td>
          </tr>
          <tr v-if="![2, 4].includes(+putData.gua_type)">
            <td class="text-muted">指定银行：</td>
            <td colspan="3">
              <select-org-bank
                :project-type="putData.gua_type"
                v-model="putData.public_bank_ids"
                placeholder="银行名称"
                @select="setPublic"
                filterable
                class="form-control-ml"
              ></select-org-bank>
            </td>
          </tr>
          <tr v-else>
            <td class="text-muted">合作银行：</td>
            <td colspan="3">
              <select-org-bank
                v-model="putData.bank_id"
                placeholder="银行名称"
                @select="setBank"
                filterable
                class="form-control-ml"
              ></select-org-bank>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
    <div class="text-center mt-5">
      <el-button @click="submit" type="primary" :loading="submitLoading" class="btn-long">
        确认
      </el-button>
      <el-button @click="beforeClose" class="btn-long">取消</el-button>
    </div>
    <approval-refuse
      :visible.sync="dialogVisible"
      @success="handleEditSuccess"
      :queryId="queryId"
    ></approval-refuse>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'

import SelectStaff from '@/components/select/SelectStaff'
import SelectOrgBank from '@/credit/components/select/SelectOrgBank'
import ApprovalRefuse from '@/credit/views/county/index/myTask/ApprovalRefuse'
import SelectGuaType from '@/credit/components/select/SelectGuaType'
import SelectOrgCredit from '@/credit/components/select/SelectOrgCredit'
import SelectCreditProduct from '@/credit/components/select/SelectCreditProduct'

export default {
  components: {
    SelectStaff,
    SelectOrgBank,
    ApprovalRefuse,
    SelectGuaType,
    SelectOrgCredit,
    SelectCreditProduct,
  },
  props: {
    visible: Boolean,
    relatedData: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      isBank: '0',
      putData: {
        is_approval: '',
        res_a: '',
        res_b: '',
        public_bank_ids: '',
        pre_approval_person: '',
        approved_date: '',
        gua_type: '',
        pre_approval_des: '',
        recommend_service: '',
        recommend_service_name: '',
        project_type_id: '',
        project_type_name: '',
      },
      approvalStatus: '',
      enumApprovalStatus: {
        '-1': '延时受理',
        2: '受理拒绝',
      },
      submitLoading: false,
      dialogVisible: false,
    }
  },
  computed: {
    ...mapGetters(['userId', 'user', 'clientId']),
    isUserTown() {
      return [3, 2].includes(this.user.orgRegionLever)
    },
    queryId() {
      return this.relatedData.customer_related_id
    },

    // 是否需要选择联保机构
    needAccessAgency() {
      return this.putData.gua_type && +this.putData.gua_type !== 2
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        if (this.relatedData.public_bank_ids) {
          this.isBank = '1'
          this.approvalStatus = this.relatedData.is_approval
        } else {
          this.isBank = '0'
        }
        Object.keys(this.putData).forEach(key => {
          this.putData[key] = this.relatedData[key] || ''
        })
        if (!+this.putData.gua_type) {
          this.putData.gua_type = ''
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {},
  created() {},
  methods: {
    handleAccessAgencyChange(val, agency) {
      this.putData.recommend_service_name = agency.service_agency_name || ''
    },
    handleEditSuccess() {
      this.$emit('success', true)
      this.closeDialog()
      this.beforeClose()
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    setBank(bank) {
      this.putData.bank_name = bank.agency_name
    },
    setPublic(bank) {
      this.putData.public_bank_names = bank.agency_name
    },
    setDes() {
      if (+this.approvalStatus === -1) {
        this.putData.pre_approval_des = `暂无时间处理，请稍后， 如有需求请联系：联系人：${this.user.corpName}, 联系电话${this.user.phoneNumber}`
      }
      if (+this.approvalStatus === 2) {
        this.putData.pre_approval_des = `项目不符合要求：联系人：${this.user.corpName}, 联系电话${this.user.phoneNumber}`
      }
    },
    submit() {
      if (+this.putData.is_approval === 1) {
        this.putData.gua_type = this.isUserTown ? this.putData.gua_type : 2
        if (!this.putData.gua_type) {
          return this.$message.warning('请选择项目类型')
        }
        if (!this.putData.res_a) {
          return this.$message.warning('请选择项目负责人A角')
        }
        if (!this.putData.res_b) {
          return this.$message.warning('请选择项目负责人B角')
        }
        if (+this.putData.gua_type === 4 && !this.putData.res_user_id_risk_point) {
          return this.$message.warning('请选择项目风控员')
        }

        const {
          recommend_service: serviceId,
          recommend_service_name: serviceName,
          ...data
        } = this.putData
        if (this.needAccessAgency) {
          data.recommend_service = serviceId
          data.recommend_service_name = serviceName
        }
        data.res_a_name = this.$refs.resA.getSelectedName()
        data.res_b_name = this.$refs.resB.getSelectedName()
        data.res_person_risk_point = this.$refs.risk.getSelectedName()
        data.service_id = this.clientId
        data.pre_approval_person = this.userId
        data.approved_date = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')

        this.submitLoading = true
        this.$api
          .updateData(
            this.$serviceName,
            'customer_related',
            this.relatedData.customer_related_id,
            data
          )
          .then(() => {
            this.$emit('success', true)
            this.$message.success('项目受理成功')
            this.beforeClose()
          })
          .catch(() => {
            this.$message.error('项目受理失败')
          })
          .finally(() => {
            this.submitLoading = false
          })
      } else {
        this.dialogVisible = true
      }
    },
    closeDialog() {
      this.dialogVisible = false
    },
    setLoanMode(_, select) {
      this.putData.project_type_name = select.load_name || ''
    },
  },
}
</script>
<style lang="scss" scoped></style>
